package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IAsyncService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import freemarker.template.Configuration;
;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class AsyncServiceImpl implements IAsyncService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private MinIOService minIOService;

    @Async
    @Override
    public void createHtml(ApArticle article, String content){
        try {
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //写入数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //合并模板
            StringWriter out = new StringWriter();
            template.process(map,out);
            //生成静态页面上传的minio
            String objectName = article.getId() + ".html";
            InputStream is = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
            String url = minIOService.upload(objectName, is, "text/html");
            //需要将生成的url地址写入到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
